#include "MyWorld.h"

namespace PeanutQuest {

	static GLuint loadTexture(const char *filename) {

		FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;
		FIBITMAP *dib(0);
		BYTE* bits(0);
		GLuint gl_texID;
		unsigned int width(0), height(0);

		fif = FreeImage_GetFileType(filename, 0);
		if(fif == FIF_UNKNOWN) {
			fif = FreeImage_GetFIFFromFilename(filename);
			return 0;
		}

		if(FreeImage_FIFSupportsReading(fif))
			dib = FreeImage_Load(fif, filename);
		if(!dib)
			return false;

		dib = FreeImage_ConvertTo24Bits(dib);
		bits = FreeImage_GetBits(dib);
		width = FreeImage_GetWidth(dib);
		height = FreeImage_GetHeight(dib);
		if((bits == 0) || (width == 0) || (height == 0))
			return 0;

		glGenTextures(1, &gl_texID);
		glBindTexture(GL_TEXTURE_2D, gl_texID);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_REPEAT);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_REPEAT);
		glTexEnvf(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_MODULATE);
		glTexImage2D(GL_TEXTURE_2D, 0, 3, width, height, 0, GL_BGR, GL_UNSIGNED_BYTE, bits);
		// FreeImage loads textures in BGR format.
		FreeImage_Unload(dib);

		return gl_texID;
	}

	MyWorld::MyWorld() : cg::Entity("World") {
	}

	MyWorld::~MyWorld() {
	}

	inline
	void MyWorld::makeTexture() {
		_textureDL = loadTexture("../../img/grass.jpg");
	}

	void MyWorld::makeMaterial() {
		
		GLfloat mat_emission[] = {1.0f,1.0f,1.0f,1.0f};
		GLfloat mat_ambient[] = {0.5f,0.5f,0.5f,1.0f};
		GLfloat mat_diffuse[] = {0.7f,0.7f,0.7f,1.0f};
		GLfloat mat_specular[] = {0.1f,1.0f,0.1f,1.0f};
		GLfloat mat_shininess[] = {100.0f};
		
		_materialDL = glGenLists(1);
		assert(_materialDL != 0);
		glNewList(_materialDL,GL_COMPILE);
			glMaterialfv(GL_FRONT,GL_EMISSION ,mat_emission);
			glMaterialfv(GL_FRONT,GL_AMBIENT,mat_ambient);
			glMaterialfv(GL_FRONT,GL_DIFFUSE,mat_diffuse);
			glMaterialfv(GL_FRONT,GL_SPECULAR,mat_specular);
			glMaterialfv(GL_FRONT,GL_SHININESS,mat_shininess);
		glEndList();
	}

	void MyWorld::init() {
		makeMaterial();
		makeTexture();	
	}

	void MyWorld::draw() {
		glPushMatrix();
		glEnable(GL_TEXTURE_2D);
		glBindTexture(GL_TEXTURE_2D, _textureDL);
		glCallList(_materialDL);
		glTranslated(-5,0,-35);
		glBegin(GL_QUADS);
		//glNormal3d( 0,1,0);
			glTexCoord2f(0.0f,0.0f); glVertex3f(0.0f,0.0f,0.0f);
			glTexCoord2f(0.0f,10000.0f); glVertex3f(100000.0f,0.0f,0.0f);
			glTexCoord2f(10000.0f,10000.0f); glVertex3f(100000.0f,0.0f,100000.0f);
			glTexCoord2f(10000.0f,0.0f); glVertex3f(0.0f,0.0f,100000.0f);
		glEnd();
		glDisable(GL_TEXTURE_2D);
		glPopMatrix();	
	}

	void MyWorld::drawOverlay() {
		glDisable(GL_LIGHTING);
		//glDisable(GL_FOG);
	}

}